from django.http import JsonResponse
from rest_framework import status, viewsets
from django.contrib import auth
from rest_framework.authentication import TokenAuthentication
from rest_framework.pagination import PageNumberPagination

from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.decorators import api_view, authentication_classes, permission_classes

from browse.models import Post
from browse.serializers import PostListSerializer, PostSerializer

from django.conf import settings


@api_view(['POST'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
def upload_avatar(request):
    file = request.FILES.get('file')
    try:
        print(settings.STATICFILES_DIRS[0])
        file_path = settings.STATICFILES_DIRS[0] + '/' + file.name
        with open(file_path, 'wb+') as f:
            f.write(file.read())
        response = {'file': file.name, 'code': 200, 'msg': '添加成功'}
    except FileNotFoundError:
        response = {'file': '', 'code': 201, 'msg':'文件路径不存在'}
    except Exception as e:
        response = {'file': '', 'code': 201, 'msg': f'添加失败：{str(e)}'}
    return Response(response)

# Create your views here.
@api_view(['POST'])
@permission_classes((AllowAny,))
@authentication_classes(())
def login(request):
    """登录"""
    data = request.data
    username = data.get('username')
    password = data.get('password')

    # 调用django进行用户认证
    # 验证成功 user返回<class 'django.contrib.auth.models.User'>
    # 验证失败 user返回None
    user = auth.authenticate(username=username, password=password)
    if user is None:
        error_info = {
            'code': 5001,
            'message': '用户名或密码错误',
        }
        return JsonResponse(error_info)

    # 用户名和密码验证成功
    # 获取用户的token 如果没有token ，表示时用户首次登录，则进行创建，并且返回token
    try:
        token_obj = Token.objects.get(user_id=user.id)
    except Exception as e:
        # token 不存在 说明是首次登录
        token_obj = Token.objects.create(user=user)
    # 获取token字符串
    token = token_obj.key
    return Response({'token': token}, status=status.HTTP_200_OK)


class PostPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'pageSize'
    page_query_param = 'pageNum'
    max_page_size = 30


class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    pagination_class = PostPagination

    # 这样保证list查询时不出现content字段，减轻查询压力
    def get_serializer_class(self):
        if self.action == 'list':
            return PostListSerializer
        else:
            return PostSerializer
        # elif self.action == 'retrieve':
        # return PostSerializer
